<?php

class UsersController extends Controller
{
	public function actionIndex()
	{
		$users = Users::model()->findAll();
		$this->render('index', array("users" => $users));
	}
	
	public function actionUpdate($id){
		$user = Users::model()->findByPk($id);
		
		//si hay posteo entonces intento guardar
		if (isset($_POST["Users"])){			
			$user->attributes = $_POST["Users"];
			$user->photo_path = (!empty($_FILES["Users"]["name"]["photo_path"])) ? $_FILES["Users"]["name"]["photo_path"] : '';
			if ($user->save()){
				if(strlen($user->photo_path) > 0){
					$uploaded = $this->uploadImage($user->photo_path);
					if ($uploaded){
						$this->updateImage($id, $user->photo_path);
					}
				}
				
				$this->redirect(array("index"));
			}				
		}		
		//si no hay posteo cargo la vista con el form
		$this->render('update', array("user" => $user));
	}
	
	public function actionCreate(){
		$user = new Users();
		if (isset($_POST["Users"])){
			
			$user->attributes = $_POST["Users"];
			$user->photo_path = (!empty($_FILES["Users"]["name"]["photo_path"])) ? $_FILES["Users"]["name"]["photo_path"] : ''; 			
			if($user->save()){
				if(strlen($user->photo_path) > 0){					
// 					$user->photo_path = CUploadedFile::getInstance($user,'photo_path');
// 					$user->photo_path->saveAs(Yii::getPathOfAlias('webroot')."/".Yii::app()->params["uploads"]."/".$user->photo_path );
					$uploaded = $this->uploadImage($user->photo_path);
					if ($uploaded){
						$this->updateImage($user->primaryKey, $user->photo_path);
					}
				}
				$this->redirect(array("index"));
			}
		}
		$this->render("create", array("user" =>$user));
	}		
			
	public function actionDelete($id){
		Users::model()->deleteByPk($id);
		$this->redirect(array("index"));
	}
	
	private function updateImage($id, $imageName){
		echo $id." -- ".$imageName; 
		//$user = Users::model()->findByPk($pk);
		$user = Users::model()->findByPk($id);
		$user->photo_path = $imageName;
		$user->save();		
	}
	
	private function uploadImage($imageName){
		$user = new Users();
		$user->photo_path = CUploadedFile::getInstance($user,'photo_path');
		$uploaded = $user->photo_path->saveAs(Yii::getPathOfAlias('webroot')."/".Yii::app()->params["uploads"]."/".$imageName );
		return $uploaded;
	}
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}